const { DataTypes } = require('sequelize')
const { sequelize } = require('../config/database')

const ChatMessage = sequelize.define('ChatMessage', {
  id: {
    type: DataTypes.STRING(50),
    primaryKey: true,
    allowNull: false
  },
  sessionId: {
    type: DataTypes.STRING(50),
    allowNull: false,
    references: {
      model: 'chat_sessions',
      key: 'id'
    }
  },
  userId: {
    type: DataTypes.STRING(50),
    allowNull: false,
    references: {
      model: 'users',
      key: 'id'
    }
  },
  role: {
    type: DataTypes.ENUM('user', 'assistant', 'system'),
    allowNull: false
  },
  content: {
    type: DataTypes.TEXT,
    allowNull: false
  },
  aiConfigId: {
    type: DataTypes.UUID,
    allowNull: true,
    references: {
      model: 'ai_configs',
      key: 'id'
    }
  },
  metadata: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: {
      tokenUsage: null,
      model: null,
      finishReason: null,
      responseTime: null
    }
  },
  isEdited: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false
  },
  editHistory: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: []
  },
  reactions: {
    type: DataTypes.JSON,
    allowNull: true,
    defaultValue: []
  },
  isDeleted: {
    type: DataTypes.BOOLEAN,
    allowNull: false,
    defaultValue: false
  },
  parentMessageId: {
    type: DataTypes.STRING(50),
    allowNull: true,
    references: {
      model: 'chat_messages',
      key: 'id'
    }
  }
}, {
  tableName: 'chat_messages',
  timestamps: true,
  createdAt: 'createdAt',
  updatedAt: 'updatedAt',
  indexes: [
    {
      fields: ['sessionId']
    },
    {
      fields: ['userId']
    },
    {
      fields: ['role']
    },
    {
      fields: ['aiConfigId']
    },
    {
      fields: ['isDeleted']
    },
    {
      fields: ['createdAt']
    },
    {
      fields: ['parentMessageId']
    }
  ]
})

module.exports = ChatMessage